package com.ivifi.shirodemo.filter;

import java.util.Iterator;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import com.ivifi.shirodemo.Server.UrlFileterService;
import com.ivifi.shirodemo.Server.UrlFilterServiceImp;
import com.ivifi.shirodemo.dto.UrlFilter;

/**
 * 进行url权限的拦截
 * @author Administrator
 *
 */
public class MyFilter extends AuthorizationFilter {
	 private static Logger log=Logger.getLogger(MyFilter.class);

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		log.debug("进行权限过滤");
		// 主体
		Subject subject = getSubject(request, response);
		
		// 角色集合
		//String rolesArray[] = (String[]) mappedValue;
		if (subject.getPrincipal() == null) {
			//用户没有登陆，放行进入user拦截器
			return false;
		} else {
			String requestUrl = httpRequest.getRequestURI();
			log.debug(requestUrl);

			UrlFileterService urlService = new UrlFilterServiceImp();
			UrlFilter url = urlService.findOne(null);

			if (url != null) {
				String role = url.getRoles();
				if(subject.hasRole(role))
					return true;

				return false;
			} else {
				// 没有此路径的权限设置，放行
				return true;
			}

		}

	}
}
